package cn.edu.nuc.ssm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.edu.nuc.ssm.dto.PageInfo;
import cn.edu.nuc.ssm.entity.Car;
import cn.edu.nuc.ssm.entity.Cartype;
import cn.edu.nuc.ssm.service.interfaces.CarService;
import cn.edu.nuc.ssm.service.interfaces.CartypeService;

@Controller
@RequestMapping("/car")
public class CarController {

	@Autowired
	private CarService carService;
	
	@Autowired
	private CartypeService cartypeService;
	
	/**跳转到添加车辆页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String toadd(Model model){
		
		List<Cartype> list = cartypeService.listAll();
		
		model.addAttribute("list", list);
		
		return "car/add";
	}
	
	/**添加车辆
	 * @param car
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public String add(Car car){
		
		int count = carService.savecar(car);
		
		if(count <= 0){
			
			return "error";
		}
		
		return "redirect:/car/list";
		
	}
	/**列出车辆信息，带分页
	 * @param current
	 * @param carName
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/list")
	public String list(@RequestParam(name="current",defaultValue="1")int current,@RequestParam(name="carName",defaultValue="")String carName,Model model){
		
		PageInfo pageInfo = carService.listWidthPage(current,carName);
		
		model.addAttribute("pager", pageInfo);
		
		return "car/list";
	}
	
	/**删除车辆信息
	 * @param id 车辆id
	 * @return
	 */
	@RequestMapping(value="/delete",method=RequestMethod.GET)
	public String delete(@RequestParam("id")int id){
		
		int count = carService.delete(id);
		
		if(count <= 0){
			
			return "error";
		}
		
		return "redirect:/car/list";
	}
	@RequestMapping(value="/update",method=RequestMethod.GET)
	public String toupate(@RequestParam("id")int id,Model model){
		
		Car car = carService.findCarByid(id);
		List<Cartype> list = cartypeService.listAll();
		
		
		model.addAttribute("car", car);
		model.addAttribute("list", list);
		
		return "car/edit";
	}
	
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public String update(Car car){
		
		int count = carService.update(car);
		
		if(count <= 0){
			
			return "error";
		}
		
		return "redirect:/car/list";
	}
	
}
